/**
 * lightbox (using ../common/alert.js)
 * @author Rox<zhangyi.cn@gmail.com>
 */
(function($) {
    $.fn.make_lightbox = function() {
        $.each($(this), function(index, item) {
            $(item).click(function(e) {
                e.preventDefault();

                var link = $(item).attr('href');
                var img  = new Image();
                img.onload = function() {
                    var width  = img.width;
                    var height = img.height;

                    // get viewport size
                    var v_width = $.getViewportWidth();
                    var v_height = $.getViewportHeight();

                    v_width = Math.min(v_width - 80, v_width * 0.8);
                    v_height = Math.min(v_height - 60, v_height * 0.8);

                    if ( width > v_width || height > v_height ) {
                        var ratio = Math.min(v_width/width,  v_height/height);
                        width  = parseInt(width * ratio, 10);
                        height = parseInt(height * ratio, 10);
                    }

                    var img_wrapper = $('<div></div>').css('width', width)
                                                      .css('height', height);
                    var img_elm = $('<img></img>').attr('width', width)
                                                  .attr('height', height)
                                                  .attr('src', link)
                                                  .appendTo(img_wrapper);
                    new dwg.Alertbox(null).loadHTML(img_wrapper, function(_this) {
                        _this.element.css('width', width).css('height', height);
                        _this.popupbox.renew();
                    }).show();
                };
                img.src = link;
            });
        });
    };
} (jQuery));
